$(function () {
	$.init();
	var isHaveAddress = false;
	var param = parseUrlSearch();
	var cacheSkus = [];
	var isFromOrder = param.from == 'order';
	var EXPRESS_MONEY = 0;

	$(document).on('click', '.j-updateAddress', updateAddress);
	$(document).on('click', '.j-buy', onPay);
	$(document).on('click', '.j-cancel', cancelOrder);
	$(document).on('click', '.j-return', onBack);
	$(document).on('change', 'select', onExpress);

	renderAddress();
	renderProducts();

	if (isFromOrder) {
		$('.title').html('订单详情');
		if (+sessionStorage.getItem('status') > 10) {
			$('.buy').hide();
		}	
	}

	function renderProducts () {
		cacheSkus = JSON.parse(sessionStorage.getItem('details'));
		var html = cacheSkus.reduce(function (memo, detail) {
			return memo + getProductHtml(detail);
		}, '');
		$('.content ul').html(html);
		$('.buy-wrap .total span').html(sessionStorage.getItem('total') * 1 + EXPRESS_MONEY);
	}

	function fetchProducts (callback) {
		$.ajax({
			url: HOST + '/api/order/get',
			data: {
				orderCode: param.orderCode
			},
			success: function (res) {
				callback && callback(res.content);
			}
		});
	}

	function getProductHtml (detail) {
		return '<li class="item" data-id="">\
					<div class="item_img">\
						<img src="'+(detail.sku_image||detail.skuImage)+'">\
					</div>\
					<div class="item_info">\
						<div class="tit">'+(detail.sku_name||detail.skuName)+'</div>\
						<div class="spec">'+(detail.spec?'规格：':'')+(detail.spec||'')+'</div>\
						<div><span class="price" data-val="'+(detail.current_price||detail.price)+'">'+(detail.current_price||detail.price)+'</span></div>\
					</div>\
					<div style="clear: both;"></div>\
					<div class="item_desc">\
						<div class="label">选购数量</div>\
						<div class="value" data-val="'+detail.qty+'">'+detail.qty+'</div>\
					</div>\
				</li>';
	}

	function renderAddress () {
		fetchAddress(function (address) {
			isHaveAddress = !!address.addressInfo;
			var html = '<div class="name">您还没有新建地址呦</div><div class="phone"></div><div class="address nowrap"></div><div class="btn j-updateAddress">新建收货地址</div>';
			if (isHaveAddress) {
				address = JSON.parse(address.addressInfo);
				html = getAddressHtml(address);
			}
			$('.address-wrap').html(html);
		});
	}

	function fetchAddress (callback) {
		$.ajax({
			url: HOST + '/api/user/address/get',
			data: {
				openid: SELFID
			},
			success: function (res) {
				callback && callback(res.content);
			}
		});
	}

	function getAddressHtml (data) {
		return '<div class="name">'+data.name+'</div>\
				<div class="phone">'+data.phone+'</div>\
				<div class="address nowrap">'+data.area+' '+data.address+'</div>' +
				(isFromOrder ? '' : '<div class="btn j-updateAddress">修改收货地址</div>');
	}

	function updateAddress () {
		window.location = './address_info.html?from='+param.from+'|sure';
	}

	function onPay () {
		if(!isHaveAddress) {
			$.alert('您还没有新建收货地址！');
			return;
		}
		createOrder(function (orderCode) {
			pay({
				price: +$('.buy-wrap .total span').html(),
				orderCode: orderCode,
				callback: function() {
					$.alert('支付成功，尽快为您发货！感谢您的支持！');
					setTimeout(function () {
						onBack();
					}, 2000);
				},
				errCallback: function () {
					$.alert('支付失败！请联系管理员！');
					cancelOrder(orderCode);
				}
			});
		});
	}

	function cancelOrder (orderCode) {
		$.ajax({
			url: HOST + '/api/mini-program/pay/fail',
			type: 'post',
			data: JSON.stringify({
			    "openid": SELFID,
			    "orderCode": orderCode,
			    "errMsg": 'cancel' 
			}),
			success: function () {
				onBack();
			}
		});
	}

	function onBack () {
		var _param = JSON.parse(sessionStorage.getItem('param'));
		sessionStorage.clear();
		if(param.from == 'car') {
			window.location = './product_car.html';
		}else if(param.from == 'cloth') {
			window.location = './product_cloth_info.html?id=' + _param.id + '&category=' + _param.category;
		}else if(param.from == 'order') {
			window.location = './order_list.html';
		}else if(param.from == 'orderdetail') {
			window.location = './order_info.html?orderCode=' + param.orderCode;
		}
	}

	function createOrder (callback) {
		if (isFromOrder) {
			callback && callback(sessionStorage.getItem('orderCode'));
			return;
		}
		var details = cacheSkus.map(function(sku) {
			return {
				skuCode: sku.sku_code,
				qty: sku.qty
			}
		});
		$.ajax({
			url: HOST + '/api/order/create',
			type: 'post',
			data: JSON.stringify({
				"openid": SELFID,
				"details": details,
				"isShoppingCart": param.from == 'car',
				"isExpress": $('select').val() == '1'
			}),
			success: function(res) {
				callback && callback(res.content.orderCode);
			}
		});
	}

	function onExpress (e) {
		var $span = $('.total span');
		var total = $span.html() * 1;
		if($(this).val() == 1) {
			total = total + EXPRESS_MONEY;
		}else {
			total = total - EXPRESS_MONEY;
		}
		$span.html(total.toFixed(2));
	}
})
